//! 离线数据特性

use super::OpCode;
use super::PROTOCOL_ID;
use crate::consts::*;
use crate::id::*;
use crate::net;
use alloc::collections::BTreeMap;
use alloc::collections::VecDeque;
use heapless::Vec;
use log::*;
use spin::Lazy;
use spin::Mutex;

pub const FEATURE_ID: u8 = 0x01;
static BUFFER: Lazy<Mutex<BTreeMap<Id, VecDeque<Vec<u8, PacketLen>>>>> =
    Lazy::new(|| Mutex::new(BTreeMap::new()));

pub(crate) fn when_recv(remote: &Id, opcode: OpCode, data: &[u8]) {
    match opcode {
        OpCode::Disable => {
            BUFFER.lock().remove(remote);
        }
        OpCode::Enable => {
            BUFFER.lock().insert(remote.clone(), VecDeque::new());
        }
        OpCode::Read => {
            if let Some(link) = net::get_link(remote) {
                let status = is_enabled(remote);
                let buf = [FEATURE_ID, OpCode::ReadResult as u8, status as _];
                let packet = net::pack(PROTOCOL_ID, &buf, remote);
                let _err = link.send(&packet.to_buf());
            }
        }
        OpCode::ReadResult => match data[0] {
            0x00 => {
                warn!("feature offline is disabled.");
            }
            0x01 => {
                warn!("feature offline is enabled.");
            }
            _ => {}
        },
        OpCode::Operate => match data[0] {
            0x01 => {
                pop(remote);
            }
            _ => {}
        },
        _ => {}
    }
}
/// 添加到缓存器
pub fn is_enabled(id: &Id) -> bool {
    if let Some(_) = BUFFER.lock().get_mut(id) {
        return true;
    }
    return false;
}
/// 添加到缓存器
pub fn push(id: &Id, buf: &[u8]) {
    if let Some(queue) = BUFFER.lock().get_mut(id) {
        queue.push_back(Vec::from_slice(buf).unwrap());
    }
}
/// 发送缓存数据
fn pop(id: &Id) {
    if let Some(queue) = BUFFER.lock().get_mut(id) {
        if let Some(buf) = queue.pop_front() {
            if let Some(link) = net::get_link(id) {
                if let Err(_) = link.send(&buf) {
                    warn!("Offline data send err.");
                }
            }
        }
    }
}
